
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.swing.JLabel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Hra.java
 *
 * Created on 15.11.2011, 15:29:00
 */
/**
 *
 * @author Riso
 */
public class Hra extends javax.swing.JFrame implements KeyListener, Runnable {

    final static int tankx = 0;
    final static int tanky = 1;
    final static int smertanku = 2;
    final static int strelax = 3;
    final static int strelay = 4;
    final static int narazje = 5;
    final static int vydrzcislo = 6;
    Tank t;
    Enemy enemy;
    Pozadie p;
    Zakladna z;
    Strela str;
    JLabel ukazVydrz = new JLabel();
    JLabel grafikaVydrz = new JLabel();
    StrelaEnemy enemyhoStrela = new StrelaEnemy(-5000, -5000);
    Zakladna zakladnaEnemy;
    int port = 61254;
    Socket socket = null;
    ServerSocket s = null;
    Rectangle tank = new Rectangle(-2000, -2000, 25, 25);
    Rectangle strela = new Rectangle(5000, 5000, 5, 5);
    Rectangle mojtank;
    Rectangle zakladna;
    boolean vyhra = false;
    boolean konec = false;
    boolean bez = true;
    PrintWriter out;
    BufferedReader in;
    int vydrz = 500;
    Thread th = new Thread(this);
    int udaje[] = {1, 1, 1, 0, 0, 0, vydrz};
    int udajemoje[] = {1, 1, 1, 0, 0, 0, vydrz};
    ArrayList<Integer> keys = new ArrayList<Integer>();

    /** Creates new form Hra */
    public Hra() {

        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        int x = 1;
        int y = 1;
        while (x % 5 != 0) {
            x = ((int) (-100 + Math.random() * 740));
        }
        while (y % 5 != 0) {
            y = ((int) (-100 + Math.random() * 790));
        }
        System.out.println(x+":"+y);
        initComponents();
        this.addKeyListener(this);
        this.setFocusable(true);
        p = new Pozadie(-x, -y);
        z = new Zakladna(this, getWidth() / 2 - 49, getHeight() / 2 - 49, 1);
        zakladnaEnemy = new Zakladna(this, 0, 0, 2);
        enemy = new Enemy(this, udaje[tankx], udaje[tanky]);
        t = new Tank(this);
        mojtank = new Rectangle(x, y, 25, 25);
        zakladna = new Rectangle(x, y, 60, 60);
        ukazVydrz.setFont(new Font("Courier New", 1, 18));
        ukazVydrz.setBounds(5, 5, 150, 20);
        grafikaVydrz.setFont(new Font("Courier New", 1, 18));
        ukazVydrz.setForeground(new Color(255, 255, 255));
        grafikaVydrz.setBounds(6, 6, 150, 20);
        this.add(ukazVydrz);
        this.add(grafikaVydrz);
        this.add(t);
        this.add(enemy);
        this.add(z);
        this.add(enemyhoStrela);
        this.add(zakladnaEnemy);
        this.add(p);
        nadviazatSpojenie();
        repaint();
        
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Host");
        setResizable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Hra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Hra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Hra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Hra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Hra().setVisible(true);

            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

    public void nadviazatSpojenie() {
        try {
            s = new ServerSocket(port);
            socket = s.accept(); // Cakame na klienta 
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                th.start();
            } catch (Exception ex) {
            }
        } catch (Exception ex) {
        }
    }
    int pomocprezakladnu = 0;

    public void ukazEnemy() {
        enemy.smer = udaje[smertanku];
        if (udaje[strelax] != 0 && udaje[strelay] != 0) {
            enemyhoStrela.setLocation(udaje[strelax] - udajemoje[tankx] + getWidth() / 2, udaje[strelay] - udajemoje[tanky] + getHeight() / 2);

        } else {
            enemyhoStrela.setLocation(-5000, -5000);
        }
        enemy.setLocation(udaje[tankx] - udajemoje[tankx] + getWidth() / 2 - 13, udaje[tanky] - udajemoje[tanky] + getHeight() / 2 - 13);
        if (pomocprezakladnu == 0) {
            zakladnaEnemy.setBounds(udaje[tankx] - udajemoje[tankx] + getWidth() / 2 - 50, udaje[tanky] - udajemoje[tanky] + getHeight() / 2 - 50, 101, 101);
            pomocprezakladnu++;

        }
    }

    public void odosliPozadie() {
        out.println(p.pozadieString());
    }

    public void zapisEnemy() {
        if (udaje[smertanku] == 1 && p.pole[(udaje[tankx] + 13) / 5][udaje[tanky] / 5] != 3 && udaje[vydrzcislo] >= 1) {
            p.zaznacit(udaje[tankx], udaje[tanky]);
        } else if (udaje[smertanku] == 2 && p.pole[(udaje[tankx] - 13) / 5][udaje[tanky] / 5] != 3 && udaje[vydrzcislo] >= 1) {
            p.zaznacit(udaje[tankx], udaje[tanky]);
        } else if (udaje[smertanku] == 3 && p.pole[(udaje[tankx]) / 5][(udaje[tanky] + 13) / 5] != 3 && udaje[vydrzcislo] >= 1) {
            p.zaznacit(udaje[tankx], udaje[tanky]);
        } else if (udaje[smertanku] == 4 && p.pole[(udaje[tankx]) / 5][(udaje[tanky] - 13) / 5] != 3 && udaje[vydrzcislo] >= 1) {
            p.zaznacit(udaje[tankx], udaje[tanky]);
        }

    }

    public void nacitajUdaje() {
        String s = "";
        try {
            s = in.readLine();

            udaje[tankx] = Integer.parseInt(s.substring(0, s.indexOf(";")));
            s = s.substring(s.indexOf(";") + 1);
            udaje[tanky] = Integer.parseInt(s.substring(0, s.indexOf(";")));
            s = s.substring(s.indexOf(";") + 1);
            udaje[smertanku] = Integer.parseInt(s.substring(0, s.indexOf(";")));
            s = s.substring(s.indexOf(";") + 1);
            udaje[strelax] = Integer.parseInt(s.substring(0, s.indexOf(";")));
            s = s.substring(s.indexOf(";") + 1);
            udaje[strelay] = Integer.parseInt(s.substring(0, s.indexOf(";")));
            s = s.substring(s.indexOf(";") + 1);
            udaje[narazje] = Integer.parseInt(s.substring(0, s.indexOf(";")));
            s = s.substring(s.indexOf(";") + 1);
            udaje[vydrzcislo] = Integer.parseInt(s.substring(0));
            if (udaje[narazje] == 1) {
                narazklient();
            }
        } catch (Exception ex) {
        }
    }

    public void doplnenieVydrze() {
        if (mojtank.intersects(zakladna) && vydrz < 500) {
            vydrz++;
        }
    }

    public void aktualizujUdaje() {
        ukazVydrz.setText("Vydrz: " + vydrz);
        grafikaVydrz.setText("Vydrz: " + vydrz);
        udajemoje[tankx] = -p.getX() + getWidth() / 2;
        udajemoje[tanky] = -p.getY() + getHeight() / 2;
        udajemoje[narazje] = 0;
        udajemoje[strelax] = 5000;
        udajemoje[strelay] = 5000;
        udajemoje[smertanku] = t.smer;
        udajemoje[vydrzcislo] = vydrz;
        mojtank.setLocation(getWidth() / 2 + 13, getHeight() / 2 + 13);
        zakladna.setLocation(z.getX() + 50, z.getY() + 50);
        if (str != null) {
            udajemoje[strelax] = -p.getX() + str.getX();
            udajemoje[strelay] = -p.getY() + str.getY();
        }
        tank.setLocation(udaje[tankx] - 12, udaje[tanky] - 12);
        strela.setLocation(udajemoje[strelax], udajemoje[strelay]);
        if (tank.intersects(strela)) {
            vyhra = true;
            konec = true;
        }

        //System.out.println("enemy>>>"+udaje[tankx]+":"+udaje[tanky]);
        //System.out.println("ja>>>>>>"+udajemoje[tankx]+":"+udajemoje[tanky]);
    }

    public String udajeString() {
        String s = "";
        StringBuilder sb = new StringBuilder(s);
        sb.append(udajemoje[tankx]);
        sb.append(";");
        sb.append(udajemoje[tanky]);
        sb.append(";");
        sb.append(udajemoje[smertanku]);
        sb.append(";");
        sb.append(udajemoje[strelax]);
        sb.append(";");
        sb.append(udajemoje[strelay]);
        sb.append(";");
        sb.append(udajemoje[narazje]);
        sb.append(";");
        sb.append(udajemoje[vydrzcislo]);
        s = sb.toString();
        return s;
    }

    public void odosliUdaje() {
        out.println(udajeString());
    }

    @Override
    public synchronized void keyTyped(KeyEvent e) {
    }

    public void naraz() {
        int x = udajemoje[strelax] / 5;
        int y = udajemoje[strelay] / 5;
        if (x > 197 || x < 3 || y > 197 || y < 3) {
            udajemoje[strelax] = 0;
            udajemoje[strelay] = 0;
            str.naraz = true;
            str = null;
        } else if (p.pole[x][y] != 3) {
            p.zaznacitVybuch(x, y);
            udajemoje[strelax] = 0;
            udajemoje[strelay] = 0;
            str.naraz = true;
            str = null;
        }

    }

    public void nacitajKoniec() {
        try {
            int ano = Integer.parseInt(in.readLine());
            if (ano == 1) {
                konec = true;
                s.close();
                socket.close();
            }
        } catch (Exception ex) {
        }

    }

    public void odosliKoniec() {
        String strin = "";
        if (konec) {
            strin = "1";
        } else {
            strin = "0";
        }
        out.println(strin);
    }

    public void narazklient() {
        int x = udaje[strelax] / 5;
        int y = udaje[strelay] / 5;
        if (x > 197 || x < 3 || y > 197 || y < 3) {
            return;
        } else if (p.pole[x][y] != 3) {
            p.zaznacitVybuch(x, y);
        }
    }

    public void zaznacZakladnu() {
        int xm = -p.getX() + getWidth() / 2 - 45;
        int ym = -p.getY() + getHeight() / 2 - 49;
        int xe = udaje[tankx] - 45;
        int ye = udaje[tanky] - 49;
        p.zaznacitZakladnu(xm, ym);
        p.zaznacitZakladnu(xe, ye);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (!keys.contains(new Integer(e.getKeyCode()))) {
            keys.add(new Integer(e.getKeyCode()));
        }
        char key = e.getKeyChar();
        switch (key) {
            case 'k':
                if (str == null && vydrz > 50) {
                    str = new Strela(this, getWidth() / 2 - 2, getHeight() / 2 - 2, udajemoje[smertanku]);
                    this.add(str, 1);
                    vydrz = vydrz - 50;
                }
                break;
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        keys.remove(new Integer(e.getKeyCode()));
    }
    boolean zaznaceneZakladne = false;

    @Override
    public void run() {
        try {
            while (bez) {
                aktualizujUdaje();
                doplnenieVydrze();
                if (str != null) {
                    naraz();
                }
                odosliPozadie();
                nacitajUdaje();
                zapisEnemy();
                odosliUdaje();
                odosliKoniec();
                nacitajKoniec();
                ukazEnemy();

                if (!zaznaceneZakladne) {
                    zaznacZakladnu();
                    zaznaceneZakladne = true;
                }
                if (p.getX() > getWidth() / 2 - 13) {
                    p.setLocation(p.getX() - 1, p.getY());
                    z.setLocation(z.getX() - 1, z.getY());
                    zakladnaEnemy.setLocation(zakladnaEnemy.getX() - 1, zakladnaEnemy.getY());
                }
                if (p.getY() > getHeight() / 2 - 16) {
                    p.setLocation(p.getX(), p.getY() - 1);
                    z.setLocation(z.getX(), z.getY() - 1);
                    zakladnaEnemy.setLocation(zakladnaEnemy.getX(), zakladnaEnemy.getY() - 1);
                }
                if (p.getX() < getWidth() / 2 + 14 - 999) {
                    p.setLocation(p.getX() + 1, p.getY());
                    z.setLocation(z.getX() + 1, z.getY());
                    zakladnaEnemy.setLocation(zakladnaEnemy.getX() + 1, zakladnaEnemy.getY());
                }
                if (p.getY() < getHeight() / 2 + 14 - 999) {
                    p.setLocation(p.getX(), p.getY() + 1);
                    z.setLocation(z.getX(), z.getY() + 1);
                    zakladnaEnemy.setLocation(zakladnaEnemy.getX(), zakladnaEnemy.getY() + 1);
                }
                //doprava
                if (keys.contains(new Integer(68))) {

                    t.smer = 1;
                    if (p.pole[(-p.getX() + 13 + getWidth() / 2) / 5][(-p.getY() + getHeight() / 2) / 5] != 3 & vydrz >= 1) {
                        p.zaznacit(-p.getX() + getWidth() / 2, -p.getY() + getHeight() / 2);
                        vydrz--;
                        p.setLocation(p.getX() - 1, p.getY());
                        z.setLocation(z.getX() - 1, z.getY());
                        zakladnaEnemy.setLocation(zakladnaEnemy.getX() - 1, zakladnaEnemy.getY());
                        if (str != null) {
                            str.setLocation(str.getX() - 1, str.getY());
                        }
                    } else if (p.pole[(-p.getX() + 13 + getWidth() / 2) / 5][(-p.getY() + getHeight() / 2) / 5] == 3) {
                        //p.zaznacit(-p.getX() + getWidth() / 2, -p.getY() + getHeight() / 2);
                        p.setLocation(p.getX() - 1, p.getY());
                        z.setLocation(z.getX() - 1, z.getY());
                        zakladnaEnemy.setLocation(zakladnaEnemy.getX() - 1, zakladnaEnemy.getY());
                        if (str != null) {
                            str.setLocation(str.getX() - 1, str.getY());
                        }
                    }
                }
                //dolava
                if (keys.contains(new Integer(65))) {

                    t.smer = 2;
                    if (p.pole[(-p.getX() - 13 + getWidth() / 2) / 5][(-p.getY() + getHeight() / 2) / 5] != 3 & vydrz >= 1) {
                        p.zaznacit(-p.getX() + getWidth() / 2, -p.getY() + getHeight() / 2);
                        vydrz--;
                        p.setLocation(p.getX() + 1, p.getY());
                        z.setLocation(z.getX() + 1, z.getY());
                        zakladnaEnemy.setLocation(zakladnaEnemy.getX() + 1, zakladnaEnemy.getY());
                        if (str != null) {
                            str.setLocation(str.getX() + 1, str.getY());
                        }
                    } else if (p.pole[(-p.getX() - 13 + getWidth() / 2) / 5][(-p.getY() + getHeight() / 2) / 5] == 3) {
                        //p.zaznacit(-p.getX() + getWidth() / 2, -p.getY() + getHeight() / 2);
                        p.setLocation(p.getX() + 1, p.getY());
                        z.setLocation(z.getX() + 1, z.getY());
                        zakladnaEnemy.setLocation(zakladnaEnemy.getX() + 1, zakladnaEnemy.getY());
                        if (str != null) {
                            str.setLocation(str.getX() + 1, str.getY());
                        }
                    }
                }
                //hore
                if (keys.contains(new Integer(87))) {

                    t.smer = 4;
                    if (p.pole[(-p.getX() + getWidth() / 2) / 5][(-p.getY() - 13 + getHeight() / 2) / 5] != 3 & vydrz >= 1) {
                        p.zaznacit(-p.getX() + getWidth() / 2, -p.getY() + getHeight() / 2);
                        vydrz--;
                        p.setLocation(p.getX(), p.getY() + 1);
                        z.setLocation(z.getX(), z.getY() + 1);
                        zakladnaEnemy.setLocation(zakladnaEnemy.getX(), zakladnaEnemy.getY() + 1);
                        if (str != null) {
                            str.setLocation(str.getX(), str.getY() + 1);
                        }
                    } else if (p.pole[(-p.getX() + getWidth() / 2) / 5][(-p.getY() - 13 + getHeight() / 2) / 5] == 3) {
                        //p.zaznacit(-p.getX() + getWidth() / 2, -p.getY() + getHeight() / 2);
                        p.setLocation(p.getX(), p.getY() + 1);
                        z.setLocation(z.getX(), z.getY() + 1);
                        zakladnaEnemy.setLocation(zakladnaEnemy.getX(), zakladnaEnemy.getY() + 1);
                        if (str != null) {
                            str.setLocation(str.getX(), str.getY() + 1);
                        }
                    }
                }
                //dole
                if (keys.contains(new Integer(83))) {

                    t.smer = 3;
                    if (p.pole[(-p.getX() + getWidth() / 2) / 5][(-p.getY() + 13 + getHeight() / 2) / 5] != 3 & vydrz >= 1) {
                        p.zaznacit(-(p.getX()) + getWidth() / 2, -(p.getY()) + getHeight() / 2);
                        vydrz--;
                        zakladnaEnemy.setLocation(zakladnaEnemy.getX(), zakladnaEnemy.getY() - 1);
                        p.setLocation(p.getX(), p.getY() - 1);
                        z.setLocation(z.getX(), z.getY() - 1);
                        if (str != null) {
                            str.setLocation(str.getX(), str.getY() - 1);
                        }
                    } else if (p.pole[(-p.getX() + getWidth() / 2) / 5][(-p.getY() + 13 + getHeight() / 2) / 5] == 3) {
                        //p.zaznacit(-(p.getX()) + getWidth() / 2, -(p.getY()) + getHeight() / 2);
                        zakladnaEnemy.setLocation(zakladnaEnemy.getX(), zakladnaEnemy.getY() - 1);
                        p.setLocation(p.getX(), p.getY() - 1);
                        z.setLocation(z.getX(), z.getY() - 1);
                        if (str != null) {
                            str.setLocation(str.getX(), str.getY() - 1);
                        }
                    }
                }
                if (konec) {
                    bez = false;
                    dispose();
                }
                th.sleep(20);
                repaint();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                socket.close();
                s.close();
            } catch (Exception e) {
            }
        }
    }
}
